package com.cwvs.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.cwvs.helper.UrlHelper;
import com.cwvs.models.ResultInfo;
import com.cwvs.utils.CommonUtils;
import com.cwvs.utils.DateUtils;
import com.cwvs.utils.MySqlPageUtil;
import com.cwvs.utils.ObjectId;
import com.cwvs.utils.Pages;

/**
 * 
 * 用户相关DAO
 */
@Repository
public class AppUserDao {
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private MySqlPageUtil mySqlPageUtil;
	@Resource
	private UrlHelper urlHelper;

	/**
	 * 用户新增
	 */
	public ResultInfo addUserInfo(Map<String, Object> o) {
		ResultInfo res = new ResultInfo();
		res.setMessage("用户新增失败");
		if (StringUtils.isBlank(MapUtils.getString(o, "USERNAME"))) {
			res.setMessage("请输入用户名");
			return res;
		}
		if (StringUtils.isBlank(MapUtils.getString(o, "PASSWORD"))) {
			res.setMessage("请输入密码");
			return res;
		}
		if (StringUtils.isNotBlank(MapUtils.getString(o, "PHONE"))
				&& !CommonUtils
						.checkMobilePhone(MapUtils.getString(o, "PHONE"))) {
			res.setMessage("请输入正确的手机号码");
			return res;
		}
		if (StringUtils.isNotBlank(MapUtils.getString(o, "EMAIL"))
				&& !CommonUtils.checkEmail(MapUtils.getString(o, "EMAIL"))) {
			res.setMessage("请输入正确的邮箱");
			return res;
		}
		if (isExistsUser(MapUtils.getString(o, "USERNAME"),
				MapUtils.getString(o, "PHONE"), MapUtils.getString(o, "EMAIL"))) {
			res.setMessage("用户已存在");
			return res;
		}
		String id = UUID.randomUUID().toString();
		StringBuffer sbf = new StringBuffer();
		sbf.append(" INSERT INTO APP_USER(");
		sbf.append(" ID,USERNAME,PHONE,EMAIL,PASSWORD,PASSWORD_SALT,CTIME,");
		sbf.append(" STATUS,UTIME )VALUES(");
		sbf.append(" ?,?,?,?,?,?,?,?,?)");
		List<Object> ls = new ArrayList<Object>();
		ls.add(id);
		ls.add(MapUtils.getString(o, "USERNAME"));
		ls.add(MapUtils.getString(o, "PHONE"));
		ls.add(MapUtils.getString(o, "EMAIL"));
		ls.add(MapUtils.getString(o, "PASSWORD"));
		ls.add(MapUtils.getString(o, "PASSWORD_SALT"));
		ls.add(new Date());
		ls.add(0);
		ls.add(new Date());
		if (jdbcTemplate.update(sbf.toString(), ls.toArray()) > 0) {
			res.setSuccess(true);
			res.setMessage("注册成功");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("USERNAME", MapUtils.getString(o, "USERNAME"));
			map.put("PHONE", MapUtils.getString(o, "PHONE"));
			map.put("EMAIL", MapUtils.getString(o, "EMAIL"));
			map.put("ID", id);
			res.setResult(map);
		}
		return res;

	}

	/**
	 * 
	 * 更新用户密码
	 */
	public ResultInfo updateUserPassword(Map<String, Object> o) {
		ResultInfo res = new ResultInfo();
		if (StringUtils.isBlank(MapUtils.getString(o, "USERNAME"))) {
			res.setMessage("请输入用户名");
		}
		if (StringUtils.isBlank(MapUtils.getString(o, "PASSWORD"))) {
			res.setMessage("请输入密码");
		}
		StringBuffer sbf = new StringBuffer();
		sbf.append(" UPDATE APP_USER SET PASSWORD=?,PASSWORD_SALT=? ");
		sbf.append(" ,UTIME=? WHERE UPPER(USERNAME)=UPPER(?)");
		if (jdbcTemplate.update(
				sbf.toString(),
				new Object[] { MapUtils.getString(o, "PASSWORD"),
						MapUtils.getString(o, "PASSWORD_SALT"), new Date(),
						MapUtils.getString(o, "USERNAME") }) > 0) {
			res.setMessage("密码修改成功");
			res.setSuccess(true);
			return res;
		}
		return res;
	}

	/**
	 * 通过token获取用户信息
	 */
	public ResultInfo getUserInfo(String token) {
		ResultInfo res = new ResultInfo();
		res.setMessage("无效的登录信息");
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT  U.ID USER_ID,U.USERNAME,U.PHONE,U.EMAIL FROM APP_TOKEN T ");
		sbf.append(" LEFT JOIN APP_USER U ON U.ID=T.USER_ID ");
		sbf.append("  WHERE T.ID =?  AND T.ETIME>=? AND T.CTIME<=? ");
		List<Map<String, Object>> ls = jdbcTemplate.queryForList(
				sbf.toString(),
				new Object[] { token, DateUtils.DateToLong14(new Date()),
						DateUtils.DateToLong14(new Date()) });
		if (!ls.isEmpty()) {
			res.setSuccess(true);
			res.setResult(ls.get(0));
			res.setResCode("0");
			res.setMessage("用户信息获取成功");
		}
		return res;
	}

	/**
	 * 用户登录
	 */
	public ResultInfo login(Map<String, Object> o) {
		String username = MapUtils.getString(o, "USERNAME");
		String password = MapUtils.getString(o, "PASSWORD");
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT ID,USERNAME,EMAIL,PHONE FROM APP_USER T ");
		sbf.append(" WHERE T.USERNAME=? AND T.PASSWORD=? ");
		List<Map<String, Object>> ls = jdbcTemplate.queryForList(
				sbf.toString(), new Object[] { username, password });
		ResultInfo res = new ResultInfo();
		res.setResCode("0");
		if (ls.isEmpty()) {
			res.setMessage("用户名或密码错误");
			return res;
		}
		res.setResult(ls.get(0));
		res.setSuccess(true);
		res.setMessage("登录成功");
		return res;
	}

	/**
	 * 生成用户TOKEN信息
	 */
	public String createToken(Map<String, Object> o) {
		String token = UUID.randomUUID().toString();
		StringBuffer sbf = new StringBuffer();
		sbf.append(" INSERT INTO APP_TOKEN (ID,USER_ID,CTIME,ETIME,LOGIN_INFO,IP_ADDRESS)");
		sbf.append(" VALUES(?,?,?,?,?,?)");
		List<Object> params = new ArrayList<Object>();
		params.add(token);
		params.add(MapUtils.getString(o, "ID"));
		params.add(DateUtils.DateToLong14(new Date()));
		params.add(DateUtils.DateToLong14(new Date(new Date().getTime() + 24
				* 60 * 60 * 1000)));
		params.add(MapUtils.getString(o, "LOGIN_INFO"));
		params.add(MapUtils.getString(o, "IP_ADDRESS"));
		jdbcTemplate.update(sbf.toString(), params.toArray());
		return token;
	}

	/**
	 * 通过用户名手机号邮箱判断用户已经存在
	 * 
	 * @return ture 表示用户存在 false 表示不存在
	 */
	public boolean isExistsUser(String username, String phone, String email) {
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT COUNT(1) FROM APP_USER T WHERE UPPER(USERNAME) =UPPER(?) ");
		List<String> ls = new ArrayList<String>();
		ls.add(username);
		if (StringUtils.isNotBlank(phone)) {
			sbf.append(" OR UPPER(PHONE)=UPPER(?) ");
			ls.add(phone);
		}
		if (StringUtils.isNotBlank(email)) {
			sbf.append(" OR UPPER(EMAIL)=(?) ");
			ls.add(email);
		}
		return jdbcTemplate.queryForInt(sbf.toString(), ls.toArray()) > 0;
	}

	/**
	 * 通过手机号获取用户信息
	 * 
	 * @return
	 */
	public Map<String, Object> getUserInfoByMobile(String mobile) {
		if (StringUtils.isBlank(mobile)) {
			return null;
		}
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT ID,USERNAME,PHONE,EMAIL,PASSWORD_SALT,PASSWORD,STATUS,BIG_IMAGE HEADER_IMAGE FROM APP_USER ");
		sbf.append(" WHERE UPPER(USERNAME)=? ");
		List<Map<String, Object>> ls = jdbcTemplate.queryForList(
				sbf.toString(), new Object[] { mobile.toUpperCase() });
		if (ls.isEmpty()) {
			return null;
		}
		Map<String,Object> map=ls.get(0);
		if(StringUtils.isNotBlank(MapUtils.getString(map, "HEADER_IMAGE")) ){
			map.put("HEADER_IMAGE", urlHelper.img01UrlRootWithPort(MapUtils.getString(map, "HEADER_IMAGE")));
		}
		return map;
	}

	/**
	 * 通过手机号获取管理用户信息
	 * 
	 * @return
	 */
	public Map<String, Object> getAdminUserByMobile(String mobile) {
		if (StringUtils.isBlank(mobile)) {
			return null;
		}
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT ID,USERNAME,PHONE,EMAIL,PASSWORD_SALT,PASSWORD FROM APP_USER ");
		sbf.append(" WHERE UPPER(USERNAME)=? AND user_type=1 AND STATUS=0 ");
		List<Map<String, Object>> ls = jdbcTemplate.queryForList(
				sbf.toString(), new Object[] { mobile.toUpperCase() });
		if (ls.isEmpty()) {
			return null;
		}
		return ls.get(0);
	}

	/**
	 * 用户列表
	 * 
	 * @return
	 */
	public Pages userList(Map<String, Object> m, Pages page) {
		StringBuilder sql = new StringBuilder();
		sql.append("  SELECT T1.ID,T1.USERNAME,T1.CTIME,T1.USER_TYPE,T1.STATUS ");
		sql.append("  FROM APP_USER T1 WHERE 1=1  ");
		List<Object> params = new ArrayList<Object>();
		if (StringUtils.isNotBlank(MapUtils.getString(m, "USERNAME"))) {
			sql.append(" AND UPPER(USERNAME) LIKE ? ");
			params.add("%"+MapUtils.getString(m, "USERNAME").toUpperCase()+"%");
		}
		if (StringUtils.isNotBlank(MapUtils.getString(m, "CTIME"))) {
			sql.append(" AND DATE_FORMAT(T1.CTIME,'%Y-%m-%d') >= ? ");
			params.add(MapUtils.getString(m, "CTIME"));
		}
		if (StringUtils.isNotBlank(MapUtils.getString(m, "ETIME"))) {
			sql.append(" AND DATE_FORMAT(T1.CTIME,'%Y-%m-%d') <= ? ");
			params.add(MapUtils.getString(m, "ETIME"));
		}
		String page_sql = mySqlPageUtil.getPageSql(page, sql.toString());
		List<Map<String, Object>> ls = jdbcTemplate.queryForList(page_sql,
				params.toArray());
		page.setPage(ls);
		page.setTotalRecord(userCount(m));
		return page;
	}

	private int userCount(Map<String, Object> m) {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) FROM APP_USER T1 WHERE 1=1 ");
		List<Object> params = new ArrayList<Object>();
		if (StringUtils.isNotBlank(MapUtils.getString(m, "USERNAME"))) {
			sql.append(" AND UPPER(USERNAME) LIKE ? ");
			params.add("%"+MapUtils.getString(m, "USERNAME").toUpperCase()+"%");
		}
		if (StringUtils.isNotBlank(MapUtils.getString(m, "CTIME"))) {
			sql.append(" AND DATE_FORMAT(T1.CTIME,'%Y-%m-%d') >= ? ");
			params.add(MapUtils.getString(m, "CTIME"));
		}
		if (StringUtils.isNotBlank(MapUtils.getString(m, "ETIME"))) {
			sql.append(" AND DATE_FORMAT(T1.CTIME,'%Y-%m-%d') <= ? ");
			params.add(MapUtils.getString(m, "ETIME"));
		}
		return jdbcTemplate.queryForInt(sql.toString(), params.toArray());
	}

	/**
	 * 更新用户状态
	 * 
	 * @param id
	 * @param status
	 * @return
	 */
	public boolean updateUserStatus(String id, boolean status) {
		StringBuffer sbf = new StringBuffer();
		sbf.append(" UPDATE APP_USER SET STATUS=? WHERE ID =? ");
		return jdbcTemplate.update(sbf.toString(), new Object[] { status, id }) > 0;
	}
	/**
	 * 意见反馈
	 * @param m
	 * @return
	 */
	public boolean saveFeedback(Map<String,Object> m){
		StringBuffer sbf=new StringBuffer();
		sbf.append(" INSERT INTO APP_FEEDBACK (ID,QUESTION,CTIME,TOKEN,Machine_INFO)");
		sbf.append(" VALUES(?,?,?,?,?)");
		return jdbcTemplate.update(
				sbf.toString(),
				new Object[] { UUID.randomUUID().toString(),
						MapUtils.getString(m, "QUESTION"), new Date(),
						MapUtils.getString(m, "TOKEN"),
						MapUtils.getString(m, "MACHINE_INFO")})>0;
		
	}
	/**
	 * 保存用户头像上传记录
	 */
	public void saveImageLog(Map<String,Object> m){
		StringBuffer sbf=new StringBuffer();
		sbf.append(" INSERT INTO APP_USER_IMAGE_LOG (ID ");
		sbf.append(" ,TOKEN,CTIME,BBIG_IMAGE,BIG_IMAGE,MEDIUM_IMAGE");
		sbf.append(" ,NORMAL_IMAGE,SAME_IMAGE,SMALL_IMAGE )VALUES(");
		sbf.append(" ?,?,?,?,?,?,?,?,?)");
		List<Object> ls=new ArrayList<Object>();
		ls.add(ObjectId.getObjectId());
		ls.add(MapUtils.getString(m, "TOKEN"));
		ls.add(new Date());
		ls.add(MapUtils.getString(m, "BBIG_IMAGE"));
		ls.add(MapUtils.getString(m, "BIG_IMAGE"));
		ls.add(MapUtils.getString(m, "MEDIUM_IMAGE"));
		ls.add(MapUtils.getString(m, "NORMAL_IMAGE"));
		ls.add(MapUtils.getString(m, "SAME_IMAGE"));
		ls.add(MapUtils.getString(m, "SMALL_IMAGE"));
		jdbcTemplate.update(sbf.toString(),ls.toArray());
	}
	/**
	 * 更新用户头像
	 */
	public void updateImage(Map<String,Object> m){
		StringBuffer sbf=new StringBuffer();
		sbf.append(" UPDATE APP_USER SET BBIG_IMAGE=? ");
		sbf.append(" ,BIG_IMAGE=?,MEDIUM_IMAGE=? ");
		sbf.append(" ,NORMAL_IMAGE=?,SAME_IMAGE=?,SMALL_IMAGE=? ");
		sbf.append(" WHERE ID=? ");
		List<Object> ls=new ArrayList<Object>();
		ls.add(MapUtils.getString(m, "BBIG_IMAGE"));
		ls.add(MapUtils.getString(m, "BIG_IMAGE"));
		ls.add(MapUtils.getString(m, "MEDIUM_IMAGE"));
		ls.add(MapUtils.getString(m, "NORMAL_IMAGE"));
		ls.add(MapUtils.getString(m, "SAME_IMAGE"));
		ls.add(MapUtils.getString(m, "SMALL_IMAGE"));
		ls.add(MapUtils.getString(m, "USER_ID"));
		jdbcTemplate.update(sbf.toString(),ls.toArray());
	}
}
